<?php

namespace app\common\model;

use app\common\model\lawyer\CategorySon;

class Goods extends BaseModel
{
    protected $append = ['images_url'];
    protected $type = [
        "images" => 'array'
    ];
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
    public function categorySon()
    {
        return $this->belongsTo(CategorySon::class);
    }
    
    public function item()
    {
        return $this->hasMany(GoodsItem::class);
    }

    public function getImageUrlAttr($value,$data)
    {
        if (empty($data['image'])) return '';
        if (substr($data['image'],0,4) == 'http') {
            return $data['image'];
        }
        return request()->domain() . $data['image'];
    }

    public function getImagesUrlAttr($value,$data)
    {
        if (empty($data['images'])) return [];
        $arr = json_decode($data['images']);
        $new_arr = [];
        foreach ($arr as $item) {
            if (substr($item,0,4) == 'http') {
                $new_arr[] = $item;
            } else {
                $new_arr[] = request()->domain() . $item;
            }
        }
        return $new_arr;
    }


    public function getContentUrlAttr($value,$data)
    {
        return str_replace('src="/uploads/', 'src="' . request()->domain() . "/uploads/",$data['content']);
    }
    
    public static function getList($page = 1,$limit=15,$order="id desc")
    {
        if ($page) {
            return Goods::order($order)
                ->where('stock',">",0)
                ->paginate(['list_rows'=>$limit,"page"=>$page]);
        } else {
            return Goods::order($order)->select();
        }
    }
}